<?php
/**
 * Created by PhpStorm.
 * User: Simpson
 * Date: 2016/9/8
 * Time: 13:41
 */

namespace App\Service;

use App\Exceptions\UserNotFoundException;
use App\Repository\AdminRepository;
use App\Repository\UserRepository;
use Illuminate\Http\Request;
use App\Model\Admin;
use App\Model\Role;
class AdminService
{

    protected $admin;

    protected $user;

    public function __construct(AdminRepository $admin, UserRepository $user)
    {
        $this->user = $user;
        $this->admin = $admin;
    }

    /**
     * 维护后台获取干事信息
     * @param Admin $admin
     * @return array|null
     */
    public function getOfficer(Admin $admin)
    {

        $result = \RepairService::checkMinister($admin);

        if(! $result) {
            return null;
        }

        $role = Role::where('name', 'repair_officer')->first();

        $officers = $role->users()->with('user')->get();

        return $officers;
    }

    /**
     * 增加管理员
     *
     * @param $number
     * @param $password
     * @return bool|static
     * @throws UserNotFoundException
     */
    public function add($number, $password)
    {
        if(!$this->user->getUserByNumber($number)){
            throw new UserNotFoundException($number);
        }

        return $this->admin->add($number, \Hash::make($password));
    }

    public function resetPassword($passwordOld, $password)
    {
        $admin = \Auth::user();

        if(\Auth::attempt(['number' => $admin->number, 'password' => $passwordOld])){

            $admin->update(['password' => \Hash::make($password)]);

            return $admin;

        }

        return false;
    }

    public function getAdminByName($roleName)
    {
        $admins = $this->admin->getAdminsByName($roleName);

        return $admins;
    }
}